/*
 * @Author: 半月狼
 * @Date: 2021-11-09 17:38:19
 * @LastEditor: 半月狼
 * @LastEditTime: 2022-03-03 13:08:49
 * @Description: 端升级
 */
import * as commonSDK from 'hybrid-sdk-common';

let upgradePad = function(){
    let platform = this.options.platform;// AC、NL
    let hadOpenStartDownloading = false;
    let filePath = '';
    let startDownloadingHandler = null;
    this.isInNTPAD = commonSDK.terminalCheck.isInApp() || this.options.debug;
    if(this.isInNTPAD){
        // 注释
        commonSDK.hybrid('AI_getAppVersion', {}, (data)=>{
            // 端appId：学习端（com.zuoyebang.nt）， 督导端（com.zuoyebang.nt.teacher）
            if("versionName" in data && "versionCode" in data && "appID" in data){
                window.ntVC = data.versionName || '';
                let _vc = data.versionCode || 0;
                let params = {"version": data.versionName || '', "vc": data.versionCode || 0};
                let channel = "channel" in data ? data.channel : "";
                let shopId = "shopId" in this.options ? this.options.shopId : '';
                if(channel){
                    window.ntChannel = channel;
                    params["channel"] = channel;
                }
                if(shopId){
                    params["shopId"] = shopId;
                }
                this.util.getData('post', this.options.upgradeApi, params, this.options.headers).then((data1)=>{
                    data1 = data1.data;
                    // var data1 = {'forceUpgrade': true, 'url': 'xxxx', 'content': {'title': '升级提醒', 'body': '1、aegagssssssssss\n2、阿瑟嘎我哥啊饿噶啊饿噶恶搞\n3、啊饿噶噶饿哇哥哈恶化\n4、啊饿噶饿噶饿噶饿噶饿噶\n5、啊问我噶饿噶饿噶饿啊饿哈恶化'}};
                    if("forceUpgrade" in data1){
                        if(data1.forceUpgrade && data1.url){
                            let content = 'content' in data1 && typeof data1.content == 'object' 
                                            ? {
                                               'title': 'title' in data1.content && typeof data1.content.title == 'string' && data1.content.title ? data1.content.title : '升级提醒',
                                               'body': 'body' in data1.content && typeof data1.content.body == 'string' &&  data1.content.body ? data1.content.body : '又有新功能上线啦，快升级至最新版，体验最新的功能吧～'
                                            } 
                                            : {
                                                'title': '升级提醒',
                                                'body': '又有新功能上线啦，快升级至最新版，体验最新的功能吧～'
                                            };
                            let contentTextAlign = content.body.indexOf('\n') != -1 ? 'ttleft' : '';
                            let $downloadingTip = document.createElement('div');
                            $downloadingTip.className = 'nt-downloading-tip ' + this.options.platform;
                            $downloadingTip.innerHTML = '<i></i><span class="tip-msg">已开始下载安装包···</span>';
                            document.body.appendChild($downloadingTip);

                            let $updateBox = document.createElement('div');  
                            $updateBox.className = 'nt-update-box ' + this.options.platform;
                            $updateBox.innerHTML = `
                                <div class="update-con-wr">
                                    <div class="update-con">
                                        <div class="update-top-icon"></div>
                                        <h2 class="update-title">${content.title}</h2>
                                        <span class="update-content ${contentTextAlign}">${content.body}</span>
                                        <button class="update-btn">立即升级</button>
                                    </div>
                                </div>
                                <div class="downloaded-con-wr">
                                    <div class="downloaded-con">
                                        <div class="downloaded-top-icon"></div>
                                        <h2 class="downloaded-title">安装提醒</h2>
                                        <span class="downloaded-content">安装包已下载完成，快快完成安装吧～</span>
                                        <button class="downloaded-btn">立即安装</button>
                                    </div>
                                </div>      
                            `;
                            document.body.appendChild($updateBox);

                            $updateBox.style.display = 'block';
                            $updateBox.querySelector(".update-con-wr").style.display = 'block';
                            $updateBox.querySelector(".update-con-wr").style.opacity = 1;

                            function clearDownloadingTip(){
                                if(startDownloadingHandler) clearTimeout(startDownloadingHandler);
                                $downloadingTip.style.display = 'none';
                                $downloadingTip.style.opacity = 0;
                            }
                            function showDownloadingTip(msg){
                                $downloadingTip.querySelector(".tip-msg").innerHTML = msg;
                                $downloadingTip.style.display = 'block';
                                $downloadingTip.style.opacity = 1;
                                startDownloadingHandler = setTimeout(()=>{
                                    $downloadingTip.style.opacity = 0;
                                    setTimeout(()=>{
                                        $downloadingTip.style.display = 'none';
                                        $downloadingTip.style.opacity = 0;
                                    }, 500);
                                }, 2000);
                            }
                            
                            // 下载过程监听～
                            let downloadingHandler = null;
                            if(downloadingHandler) clearInterval(downloadingHandler);
                            let $this = this;
                            function downloadListener(downloadUrl){
                                $updateBox.style.display = 'none';
                                // 注释
                                if("platform" in $this.options && $this.options.platform == 'AC'){
                                    if(_vc < 86){
                                        commonSDK.hybrid('AI_OpenSystemBrowser',  {"url": downloadUrl}, (data2)=>{
                                            $updateBox.querySelector(".update-con-wr").style.display = 'none';
                                            $updateBox.querySelector(".update-con-wr").style.opacity = 0;
                                        });
                                    }
                                    if(_vc >= 86){
                                        commonSDK.hybrid('NL_startDownloadFile', {'downloadUrl': downloadUrl}, (data2)=>{
                                            $updateBox.querySelector(".update-con-wr").style.display = 'none';
                                            $updateBox.querySelector(".update-con-wr").style.opacity = 0;
                                            if(data2 && 'downloadType' in data2){
                                                if(data2.downloadType == 1){// 开始下载
                                                    if(!hadOpenStartDownloading){
                                                        hadOpenStartDownloading = true;
                                                        showDownloadingTip("已开始下载安装包···");
                                                        downloadingHandler = setInterval(()=>{
                                                            downloadListener(downloadUrl)
                                                        }, 600);
                                                    }
                                                }else if(data2.downloadType == 5){// 下载完成

                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载完成！！");

                                                    // 注释
                                                    if("filePath" in data2 && data2.filePath){
                                                        filePath = data2.filePath;

                                                        $updateBox.style.display = 'block';
                                                        $updateBox.querySelector(".downloaded-con-wr").style.display = 'block';
                                                        $updateBox.querySelector(".downloaded-con-wr").style.opacity = 1;

                                                    // 注释
                                                    }else{
                                                        console.log("端升级下载失败！！，本地文件为空。。。");
                                                        showDownloadingTip("下载失败，安装文件为空！");
                                                    }
                                                }else if(data2.downloadType == 2){//下载进度
                                                    console.log("已经下载：" + data2.finishedSize/data2.totalSize + "%");
                                                    //showDownloadingTip("已经下载：" + data2.finishedSize/data2.totalSize + "%");
                                                }else if(data2.downloadType == 4){// 下载失败
                                                    console.log("端升级下载失败！！");
                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载失败！");
                                                }else if(data2.downloadType == 3){
                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载被终止！");
                                                }
                                            }
                                        });
                                    }
                                }else{

                                    if(_vc <= 82){
                                        commonSDK.hybrid('AI_OpenSystemBrowser',  {"url": downloadUrl}, (data2)=>{
                                            $updateBox.querySelector(".update-con-wr").style.display = 'none';
                                            $updateBox.querySelector(".update-con-wr").style.opacity = 0;
                                            $updateBox.style.display = 'none';
                                        });
                                    }
                                    if(_vc >= 92){
                                        commonSDK.hybrid('NL_startDownloadFile', {'downloadUrl': downloadUrl}, (data2)=>{
                                            $updateBox.querySelector(".update-con-wr").style.display = 'none';
                                            $updateBox.querySelector(".update-con-wr").style.opacity = 0;
                                            $updateBox.style.display = 'none';
                                            if(data2 && 'downloadType' in data2){
                                                if(data2.downloadType == 1){// 开始下载
                                                    if(!hadOpenStartDownloading){
                                                        hadOpenStartDownloading = true;
                                                        showDownloadingTip("已开始下载安装包···");
                                                        downloadingHandler = setInterval(()=>{
                                                            downloadListener(downloadUrl)
                                                        }, 600);
                                                    }
                                                }else if(data2.downloadType == 5){// 下载完成

                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载完成！！");

                                                    // 注释
                                                    if("filePath" in data2 && data2.filePath){
                                                        filePath = data2.filePath;

                                                        $updateBox.style.display = 'block';
                                                        $updateBox.querySelector(".downloaded-con-wr").style.display = 'block';
                                                        $updateBox.querySelector(".downloaded-con-wr").style.opacity = 1;

                                                    // 注释
                                                    }else{
                                                        console.log("端升级下载失败！！，本地文件为空。。。");
                                                        showDownloadingTip("下载失败，安装文件为空！");
                                                    }
                                                }else if(data2.downloadType == 2){//下载进度
                                                    console.log("已经下载：" + data2.finishedSize/data2.totalSize + "%");
                                                    //showDownloadingTip("已经下载：" + data2.finishedSize/data2.totalSize + "%");
                                                }else if(data2.downloadType == 4){// 下载失败
                                                    console.log("端升级下载失败！！");
                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载失败！");
                                                }else if(data2.downloadType == 3){
                                                    if(downloadingHandler) clearInterval(downloadingHandler);
                                                    showDownloadingTip("下载被终止！");
                                                }
                                            }
                                        });
                                    }
                                }
                            }

                            setTimeout(()=>{
                                let $udwr = $updateBox.querySelector(".downloaded-con-wr");
                                let $udBtn = $udwr.querySelector("button");
                                this.util.tclick($udBtn, ()=>{

                                }, ()=>{}, null, (e1)=>{

                                    $udwr.style.opacity = 0;
                                    clearDownloadingTip();

                                    // 注释
                                    if(filePath){
                                        commonSDK.hybrid('NL_installApk', {'apkPath': filePath}, (data3)=>{

                                            setTimeout(()=>{
                                                $udwr.style.display = 'none';
                                                $udwr.style.opacity = 0;
                                                $updateBox.style.display = 'none';

                                                // 注释
                                                if(data3 && 'result' in data3){
                                                    if(data3.result == 1){

                                                        console.log('------安装中。。。。')
                                                        showDownloadingTip("正在安装中···");

                                                    // 注释
                                                    }else if(data3.result == 2){
                                                        console.log("-------用户拒绝，安装失败！！");
                                                        showDownloadingTip("您已拒绝，安装失败！");
                                                    }
                                                }
                                            }, 500);
                                        
                                        // 注释
                                        });
                                    }else{
                                        console.log("-------下载失败，安装文件为空！");
                                    }
                                }, null, (e2)=>{}, "click");

                                let $uuwr = $updateBox.querySelector(".update-con-wr");
                                let $uuBtn = $uuwr.querySelector("button");
                                this.util.tclick($uuBtn, ()=>{

                                }, ()=>{}, null, (e1)=>{

                                    $uuwr.style.opacity = 0;
                                    clearDownloadingTip();
                                    //downloadListener();

                                    // 注释
                                    downloadListener(data1.url);
                                }, null, (e2)=>{}, "click");

                            }, 500);
                        
                        // 注释
                        }
                    }
                }).catch((err)=>{
                    console.log(err);
                });   
            }
        });
    }
};
export default upgradePad;